import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:seedfour/app/models/file_list_entity.dart';
import 'package:path/path.dart' as p;

import '../../constants.dart';
import '../../theme.dart';
import 'logic.dart';

class FolderListPage extends StatelessWidget {
  FolderListPage({Key? key}) : super(key: key);

  final logic = Get.find<FolderListLogic>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(logic.title),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            size: 16.w,
          ),
          onPressed: () {
            Get.back();
          },
        ),
        // 搜索按钮
        actions: [
          IconButton(
            icon: SvgPicture.asset(
              'assets/icons/ic_search.svg',
              width: 22.w,
              height: 22.w,
            ),
            onPressed: () => logic.toFileSearch(),
          ),
        ],
      ),
      body: Obx(() {
        if (logic.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        } else {
          return Ink(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(kRadiusMedium)),
              color: Colors.white,
            ),
            child: ListView.builder(
              controller: logic.scrollController,
              itemBuilder: _renderRow,
              itemCount: logic.files.length,
            ),
          );
        }
      }),
    );
  }

  Widget _buildListItem(FileData item) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildFileIcon(item),
        SizedBox(width: kSpaceSmall),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                item.fileName ?? item.name ?? '',
                maxLines: 3,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(fontWeight: AppFont.fontSemiBold),
              ),
              SizedBox(height: kSpaceTiny),
              Text(
                DateFormat('yyyy-MM-dd HH:mm').format(
                    DateTime.fromMillisecondsSinceEpoch(item.createdAt!)),
                style: TextStyle(color: Colors.grey, fontSize: kFontSizeMini),
              ),
            ],
          ),
        ),
        if(item.fileId != null) ...[
          SizedBox(width: kSpaceSmall),
          Align(
            alignment: Alignment.centerRight,
            child: Obx(() {
              if (logic.downloadingFileId.value == item.fileId) {
                return SizedBox(
                  width: 20.w,
                  height: 20.w,
                  child: CircularProgressIndicator(
                    value: logic.downloadProgress.value,
                    strokeWidth: 2,
                    backgroundColor: Colors.grey[200],
                    valueColor: const AlwaysStoppedAnimation<Color>(AppColor.colorMain),
                  ),
                );
              }
              return IconButton(
                iconSize: 20.w,
                icon: const Icon(
                  Icons.file_download_outlined,
                  color: AppColor.colorFontGrey,
                ),
                onPressed: () => logic.downloadFile(item),
              );
            }),
          ),
        ],
      ],
    );
  }

  Widget _buildFileIcon(FileData file) {
    if (file.fileId == null) {
      return Image.asset(
        'assets/images/folder.png',
        width: 40.w,
        height: 40.w,
      );
    }

    final fileName = file.fileName ?? '';

    return Image.asset(
      switch (p.extension(fileName)) {
        '.docx' => 'assets/icons/ic_word.png',
        '.doc' => 'assets/icons/ic_word.png',
        '.pdf' => 'assets/icons/ic_pdf.png',
        '.ppt' => 'assets/icons/ic_ppt.png',
        '.pptx' => 'assets/icons/ic_ppt.png',
        '.xls' => 'assets/icons/ic_excel.png',
        '.xlsx' => 'assets/icons/ic_excel.png',
        '.zip' => 'assets/icons/ic_zip.png',
        '.rar' => 'assets/icons/ic_zip.png',
        '' => 'assets/icons/ic_zip.png',
        String() => 'assets/icons/ic_zip.png',
      },
      width: 40.w,
      height: 40.w,
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index < logic.files.length) {
      return InkWell(
        onTap: () => logic.toFileList(index),
        child: Padding(
          padding: EdgeInsets.all(kSpaceSmall),
          child: _buildListItem(logic.files[index]),
        ),
      );
    } else {
      return _getMoreWidget();
    }
  }

  Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(kSpaceMedium),
        child: Text(
          logic.bottomTips.value,
          style: TextStyle(fontSize: kFontSizeSmall, color: Colors.grey),
        ),
      ),
    );
  }
}
